﻿using System;
using System.Collections.Generic;
using System.Web.Mvc;
using EasySite.Infrastructure;
using EasySite.Services;
using EasySite.Services.Implementations;
using EasySite.Web.Caches;
using EasySite.Web.Controllers;
using Microsoft.Practices.Unity;

namespace EasySite.Web
{
    public class EasySiteContext : IDisposable
    {
        private readonly IUnityContainer _unityContainer = new UnityContainer();

        private static readonly EasySiteContext _easySiteContext;
        public static EasySiteContext Current
        {
            get { return _easySiteContext; }
        }

        private MenuCache _menuCache;
        public MenuCache MenuCache
        {
            get { return _menuCache; }
        }

        private PageCategoryCache _pageCategoryCache;
        public PageCategoryCache PageCategoryCache
        {
            get { return _pageCategoryCache; }
        }

        private SessionCaches.SessionCaches _sessionCaches;
        public SessionCaches.SessionCaches SessionCaches
        {
            get { return _sessionCaches; }
        }

        private DefinedControllerCache _definedControllerCache;
        public DefinedControllerCache DefinedControllerCache
        {
            get { return _definedControllerCache; }
        }

        static EasySiteContext()
        {
            _easySiteContext = new EasySiteContext();
        }


        public void Initialize()
        {
            DependencyResolver.SetResolver(new UnityDependencyResolver(_unityContainer));
            ControllerBuilder.Current.SetControllerFactory(new DefaultControllerFactory(new UnityControllerActivator()));
            RegisterServices(_unityContainer);
            
            _menuCache = new MenuCache();
            _pageCategoryCache = new PageCategoryCache();
            _sessionCaches = new SessionCaches.SessionCaches();
            _definedControllerCache = new DefinedControllerCache(typeof (HomeController));
        }

        #region private metnods

        private static void RegisterServices(IUnityContainer unityContainer)
        {
            unityContainer.RegisterType<IUserService, UserService>();
            unityContainer.RegisterType<IMenuService, MenuService>();
            unityContainer.RegisterType<IPageCategoryService, PageCategoryService>();
            unityContainer.RegisterType<IPageService, PageService>();
        }

        #endregion

        #region Implementation of IDisposable

        public void Dispose()
        {
            _unityContainer.Dispose();
        }

        #endregion
    }
}
